package com.morning.dp.tools.dp.context;

import java.util.List;
import java.util.Map;

/**
 * AbstractContext
 *
 * @author @阿秋
 * @date 2021/2/4
 */
public abstract class AbstractContext implements InterruptableContext, ParameterizeContext {
    /**
     * 参数
     */
    private final Map<String, Object> params;

    /**
     * 是否已经结束
     */
    private volatile boolean interrupt;

    public AbstractContext(Map<String, Object> params) {
        this.params = params;
    }

    @Override
    public void interrupt() {
        this.interrupt = true;
    }

    @Override
    public boolean isInterrupt() {
        return this.interrupt;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <P> P getParam(String paramName, Class<P> paramType) {
        return (P) params.get(paramName);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <P> P getParam(Class<P> paramType) {
        return (P) params.get(getDefaultParamName(paramType));
    }

    @SuppressWarnings("unchecked")
    @Override
    public <P> List<P> getListParam(String paramName, Class<P> paramType) {
        return (List<P>) params.get(paramName);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <P> List<P> getListParam(Class<P> paramType) {
        return (List<P>) params.get(getDefaultParamName(paramType));
    }

    @Override
    public void setParam(String paramName, Object param) {
        params.put(paramName, param);
    }

    @Override
    public void setParam(Object param) {
        if (param != null) {
            params.put(getDefaultParamName(param.getClass()), param);
        }
    }

    protected String getDefaultParamName(Class<?> paramType) {
        return paramType.getName();
    }
}
